package com.shensi.appCollect.service.impl;

import com.shensi.appCollect.constantEnum.integralTypeEnum;
import com.shensi.appCollect.dao.AppUserInfoMapper;
import com.shensi.appCollect.dao.CustomerPointsRecordMapper;
import com.shensi.appCollect.dao.StationMapper;
import com.shensi.appCollect.enums.WxTemplateEnum;
import com.shensi.appCollect.pojo.AppUserInfo;
import com.shensi.api.admin.domian.integral.dto.CustomerPointsRecord;
import com.shensi.appCollect.pojo.Station;
import com.shensi.appCollect.service.CustomerPointsRecordService;
import com.shensi.appCollect.utils.weixinapp.WxPushUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("customerPointsRecordService")
@Slf4j
public class CustomerPointsRecordServiceImpl implements CustomerPointsRecordService {
    @Resource
    private CustomerPointsRecordMapper customerPointsRecordMapper;

    @Resource
    private WxPushUtil wxPushUtil;
    @Resource
    private StationMapper stationMapper;
    @Autowired
    private CustomerPointsRecordService customerPointsRecordService;
    @Resource
    private AppUserInfoMapper appUserInfoMapper;

    //查询客户在该油站积分记录
    @Override
    public List<CustomerPointsRecord> getCustomerPointsRecordList(CustomerPointsRecord customerPointsRecord) {
        return customerPointsRecordMapper.getCustomerPointsRecordList(customerPointsRecord);
    }

    //新增客户积分记录
    @Override
    public void insertCustomerPointsRecordInfo(CustomerPointsRecord customerPointsRecord) {
        customerPointsRecordMapper.insertCustomerPointsRecordInfo(customerPointsRecord);
    }

    //获取用户积分记录
    @Override
    public List<CustomerPointsRecord> getUserIntegralDetailList(CustomerPointsRecord customerPointsRecord) {
        return customerPointsRecordMapper.getUserIntegralDetailList(customerPointsRecord);
    }


    @SneakyThrows
    @Override
    @Transactional
    public CustomerPointsRecord updateIntegral(Integer type, Integer points, Station station, AppUserInfo userInfo, Integer oidPoints) {
        int newpoints = 0;
        String usageType="+";
        if (type ==1){
            newpoints = oidPoints + points;
        } else if (type == 0){
            newpoints = oidPoints - points;
            usageType="-";
        }
        CustomerPointsRecord customerPointsRecord = setCustomerPointsRecord(type, points, station, userInfo, newpoints);
        log.info("POS机记录修改积分：{}",customerPointsRecord);
        customerPointsRecordMapper.insertCustomerPointsRecordInfo(customerPointsRecord);
        //更新用户积分
        log.info("POS机修改用户积分 油企id：{}，用户手机号：{}，会员编码：{}，积分值：{}",station.getEnterpriseId(), userInfo.getMobilePhone(),userInfo.getMemberCode(),newpoints);
         customerPointsRecordMapper.updateIntegral(station.getEnterpriseId(), userInfo.getMobilePhone(),userInfo.getMemberCode(),newpoints);
        customerPointsRecordService.sendwxgzh(station.getStationId(),userInfo.getMobilePhone(),points,newpoints,usageType);

        return customerPointsRecord;
    }

    @Override
    public CustomerPointsRecord getOne(CustomerPointsRecord customerPointsRecord) {
        return customerPointsRecordMapper.getOne(customerPointsRecord);
    }

    @Override
    public void sendwxgzh(Integer stationId,String mobilePhone ,Integer integral,Integer totalIntegral,String usageType) {
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Station station = stationMapper.selectStationById(stationId);
        AppUserInfo appUserInfo=new AppUserInfo();
        appUserInfo.setMobilePhone(mobilePhone);
        appUserInfo.setStationId(station.getEnterpriseId());
        List<AppUserInfo> appUserInfos = appUserInfoMapper.selectAppUserInfoByMobilePhoneAndStationId(appUserInfo);
        if(appUserInfos.size()>0){
            appUserInfo=appUserInfos.get(0);
            Map<String, String> templateParams = new HashMap<>();
            templateParams.put("integral", usageType+integral.toString());
            templateParams.put("totalIntegral",totalIntegral.toString());
            templateParams.put("stationName",station.getStationName());
            templateParams.put("createTime",simpleDateFormat.format(new Date()));
            log.info("积分变动-微信模板参数：{}", templateParams);
            templateParams.put("openid", appUserInfo.getBlogOpenid());
            wxPushUtil.sendTemplateMsg(station.getEnterpriseId(), templateParams, WxTemplateEnum.INTEGRAL_CHANGE);
        }
    }

    /**
     *  构建更新积分记录表对象
     * @param type      调整类型 数据库字段为 + -  (我也搞不懂为啥要用符号)
     * @param points    积分
     * @param station   油站信息
     * @param userInfo  用户信息
     * @param newpoints 更新后积分
     * @return
     */
    public CustomerPointsRecord setCustomerPointsRecord(Integer type, Integer points, Station station, AppUserInfo userInfo, Integer newpoints){
        CustomerPointsRecord pointsRecord = CustomerPointsRecord.builder()
                .unionId(userInfo.getUnionId())
                .customerName(userInfo.getNickName())
                .recordType(type == 1 ? "+" : "-")
                .integral(points)
                .createTime(new Date())
                .stationId(station.getStationId())
                .stationName(station.getStationName())
                .mobilePhone(userInfo.getMobilePhone())
                .surplusIntegral(newpoints)
                .action(type == 1 ? integralTypeEnum.MANUAL_ADDITION : integralTypeEnum.MANUAL_REDUCTION)
                .build();
        return pointsRecord;
    }

}
